﻿using BCCommon;
using BCCommon.Enums;
using BCData.Trading.SaleGoods.SaleGoods;
using BCDto.Trading.SaleGoods.SaleGoods;
using BCEntity.Trading.SaleGoods.SaleGoods;
using BCEntity.Common.EntityNameConst;
using BCService.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BCData.Trading.SaleGoods.SaleGoodsNorm;
using BCEntity.Trading.SaleGoods.SaleGoodsNorm;
using BCData.Trading.SaleGoods.SaleGoodsCategory;
using BCCommon.NPinyin;
using BCDto.Trading.SaleGoods.SaleGoodsNorm;
using BCData.Trading.SaleShoppingCart;

namespace BCService.Trading.SaleGoods.SaleGoods
{
    public class SaleGoodsService : ISaleGoodsService
    {
        private readonly IDatabaseContext databaseContext;
        private readonly IApplicationContextService applicationContextService;
        private readonly IRedisService redisService;
        private readonly ISaleGoodsCategoryData saleGoodsCategoryData;
        private readonly ISaleGoodsData saleGoodsData;
        private readonly ISaleGoodsNormData saleGoodsNormData;
        private readonly ISaleShoppingCartData saleShoppingCartData;
        private readonly string key = string.Format("{0}", EntityNameConst.SaleGoodsEntity);
        private readonly string normKey = string.Format("{0}", EntityNameConst.SaleGoodsNormEntity);
        public SaleGoodsService(IDatabaseContext databaseContext,
            IApplicationContextService applicationContextService,
            IRedisService redisService,
            ISaleGoodsCategoryData saleGoodsCategoryData,
            ISaleGoodsData saleGoodsData,
            ISaleGoodsNormData saleGoodsNormData,
            ISaleShoppingCartData saleShoppingCartData)
        {
            this.databaseContext = databaseContext;
            this.applicationContextService = applicationContextService;
            this.redisService = redisService;
            this.saleGoodsCategoryData = saleGoodsCategoryData;
            this.saleGoodsData = saleGoodsData;
            this.saleGoodsNormData = saleGoodsNormData;
            this.saleShoppingCartData = saleShoppingCartData;
        }

        #region 检查销售商品是否存在
        public bool Exists(long saleGoodsId)
        {
            return this.saleGoodsData.Exists(saleGoodsId).GetAwaiter().GetResult();
        }
        #endregion

        #region 检查此SKU销售商品是否存在
        public bool SKUExists(string sku)
        {
            return this.saleGoodsData.SKUExists(sku).GetAwaiter().GetResult();
        }
        #endregion

        #region 销售商品相关信息
        #region 添加销售商品
        public SaleGoodsDto Add(SaleGoodsRequestDto requestDto)
        {
            if (requestDto.Norms==null || !requestDto.Norms.Any())
            {
                throw new ArgumentException("商品规格不能为空!");
            }
            if (!this.saleGoodsCategoryData.Exists(requestDto.SaleGoodsCategoryId).Result)
            {
                throw new ArgumentException("此销售商品分类不存在!");
            }
            if (this.SKUExists(requestDto.Sku))
            {
                throw new ArgumentException("此SKU销售商品已存在!");
            }
            List<SaleGoodsNormEntity> saleGoodsNormEntities = requestDto.Norms.As<List<SaleGoodsNormEntity>>();
            SaleGoodsNormEntity mainGoodsNormEntity = saleGoodsNormEntities.First();
            var categoryEntity = this.saleGoodsCategoryData.GetEntity(requestDto.SaleGoodsCategoryId).Result;
            var entity = requestDto.As<SaleGoodsEntity>();
            entity.CategoryName = categoryEntity.CategoryName;
            entity.CategoryNamePinyin = categoryEntity.CategoryNamePinyin;
            entity.GoodsNamePinyin = Pinyin.GetCompactPinyin(entity.GoodsName);
            entity.CreateAdminName = applicationContextService.Admin.FullName;
            entity.CreateAdminId = applicationContextService.Admin.AdminId;
            this.ResetGoodsDisplayInfo(entity, mainGoodsNormEntity, saleGoodsNormEntities);
            
            databaseContext.BeginTransaction();
            var result = this.saleGoodsData.Add(entity).Result;
            this.AddGoodsNorm(result,saleGoodsNormEntities);
            databaseContext.Commit();
            return result.As<SaleGoodsDto>();
        }
        #endregion

        #region 修改销售商品
        public SaleGoodsDto Update(SaleGoodsPutDto putDto)
        {
            if (!this.saleGoodsCategoryData.Exists(putDto.SaleGoodsCategoryId).Result)
            {
                throw new ArgumentException("此销售商品分类不存在!");
            }
            
            if (!this.Exists(putDto.SaleGoodsId))
            {
                throw new ArgumentException("此记录不存在!");
            }

            var oldDto = this.Get(putDto.SaleGoodsId);
            if (oldDto.Sku != putDto.Sku)
            {
                if (this.SKUExists(putDto.Sku))
                {
                    throw new ArgumentException("此SKU销售商品已存在!");
                }
            }
           
            if (oldDto.SaleGoodsCategoryId != putDto.SaleGoodsCategoryId)
            {
                if(this.saleShoppingCartData.GoodsExists(putDto.SaleGoodsId).Result)
                {
                    throw new ArgumentException("此商品已存在销售记录，不允许更改所属分类!");
                }
                var goodsInCartExists = false;
                if (goodsInCartExists)
                {
                    throw new ArgumentException("此商品已存在销售记录，不允许更改所属分类!");
                }
                var categoryEntity = this.saleGoodsCategoryData.GetEntity(putDto.SaleGoodsCategoryId).Result;
                oldDto.SaleGoodsCategoryId = categoryEntity.SaleGoodsCategoryId;
                oldDto.CategoryName = categoryEntity.CategoryName;
                oldDto.CategoryNamePinyin = categoryEntity.CategoryNamePinyin;
            }
            oldDto.GoodsName = putDto.GoodsName;
            oldDto.GoodsNamePinyin = Pinyin.GetCompactPinyin(putDto.GoodsName);
            oldDto.Sku = putDto.Sku;
            oldDto.EditAdminName = applicationContextService.Admin.FullName;
            oldDto.EditAdminId = applicationContextService.Admin.AdminId;
           
            var entity = oldDto.As<SaleGoodsEntity>();
            databaseContext.BeginTransaction();
            var result = this.saleGoodsData.Update(entity).GetAwaiter().GetResult().As<SaleGoodsDto>();
            bool normResult = this.saleGoodsNormData.UpdateGoodsInfo(entity).Result;
            if (!normResult)
            {
                throw new ArgumentException("修改销售商品信息失败!");
            }
            databaseContext.Commit();
            string cacheKey = this.redisService.GetKey(key, entity.SaleGoodsId);
            this.redisService.DeleteAsync(cacheKey);
            return result;
        }
        #endregion

        #region 删除销售商品
        public bool Delete(long saleGoodsId)
        {
            if (!this.Exists(saleGoodsId))
            {
                throw new ArgumentException("此记录不存在!");
            }
            if (this.saleShoppingCartData.GoodsExists(saleGoodsId).Result)
            {
                throw new ArgumentException("此商品已存在销售记录，不允许删除，仅支持禁用!");
            }
            var result = this.saleGoodsData.Delete(saleGoodsId).GetAwaiter().GetResult();
            string cacheKey = this.redisService.GetKey(key, saleGoodsId);
            this.redisService.DeleteAsync(cacheKey);
            return result;
        }
        #endregion

        #region 获取销售商品
        public SaleGoodsDto Get(long saleGoodsId)
        {
            string cacheKey = this.redisService.GetKey(key, saleGoodsId);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var data = this.saleGoodsData.GetEntity(saleGoodsId).GetAwaiter().GetResult();
                return data;
            }, TimeSpan.FromMinutes(30));
            return result.As<SaleGoodsDto>();
        }
        #endregion

        #region 获取销售商品列表
        public IEnumerable<SaleGoodsDto> GetList()
        {
            var result = this.redisService.TryGet(key, () =>
            {
                return this.saleGoodsData.GetList().GetAwaiter().GetResult();
            }, TimeSpan.FromMinutes(30));
            return result.As<IEnumerable<SaleGoodsDto>>();
        }
        #endregion

        #region 获取销售商品分页
        public PageableList<SaleGoodsDto> Query(long? saleGoodsCategoryId, string categoryName, string goodsName, string sku, bool? enabled, DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
        {
            string cacheKey = this.redisService.GetKey(key, saleGoodsCategoryId, categoryName, goodsName, sku, enabled, start, end, sortName, ascending, pageIndex, pageSize);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var data = this.saleGoodsData.Query(saleGoodsCategoryId, categoryName, goodsName, sku, enabled, start, end, sortName, ascending, pageIndex, pageSize).GetAwaiter().GetResult();
                return new PageableList<SaleGoodsDto>
                {
                    Count = data.Item2,
                    Items = data.Item1.As<IEnumerable<SaleGoodsDto>>(),
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    ServerTime = DateTime.Now
                };
            }, TimeSpan.FromMinutes(30));

            return result;
        }
        #endregion

        #region 获取销售商品分页(前端销售站点使用)
        public PageableList<SaleGoodsViewDto> GetMakeStaticPageListForSaleGoodsQuery(long? saleGoodsCategoryId, int pageIndex, int pageSize)
        {
            string cacheKey = this.redisService.GetKey(key, saleGoodsCategoryId,  pageIndex, pageSize);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var data = this.saleGoodsData.Query(saleGoodsCategoryId,null,null,null, null, null, null, null, null, pageIndex, pageSize).GetAwaiter().GetResult();
                var list = data.Item1.As<List<SaleGoodsViewDto>>();
                foreach(var item in list)
                {
                    item.Styles = this.GetGoodsNormList(item.SaleGoodsId).As<List<SaleGoodsNormViewDto>>();
                }
                return new PageableList<SaleGoodsViewDto>
                {
                    Count = data.Item2,
                    Items = list,
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    ServerTime = DateTime.Now
                };
            }, TimeSpan.FromMinutes(30));

            return result;
        }
        #endregion

        #region 启用销售商品
        public bool Enabled(long saleGoodsId)
        {
            if (!this.Exists(saleGoodsId))
            {
                throw new ArgumentException("此记录不存在!");
            }
            databaseContext.BeginTransaction();
            var result = this.saleGoodsData.Enabled(saleGoodsId).GetAwaiter().GetResult();
            this.saleShoppingCartData.UpdateSaleGoodsDisabled(saleGoodsId,false).GetAwaiter().GetResult();
            databaseContext.Commit();
            string cacheKey = this.redisService.GetKey(key, saleGoodsId);
            this.redisService.DeleteAsync(cacheKey);
            return result;
        }
        #endregion

        #region 禁用销售商品
        public bool Disabled(long saleGoodsId)
        {
            if (!this.Exists(saleGoodsId))
            {
                throw new ArgumentException("此记录不存在!");
            }
            databaseContext.BeginTransaction();
            var result = this.saleGoodsData.Disabled(saleGoodsId).GetAwaiter().GetResult();
            this.saleShoppingCartData.UpdateSaleGoodsDisabled(saleGoodsId,true).GetAwaiter().GetResult();
            databaseContext.Commit();
            string cacheKey = this.redisService.GetKey(key, saleGoodsId);
            this.redisService.DeleteAsync(cacheKey);
            return result;
        }
        #endregion
        #endregion

        #region 销售商品规格相关信息
        #region 添加销售商品规格
        private List<SaleGoodsNormEntity> AddGoodsNorm(SaleGoodsEntity goodsEntity, List<SaleGoodsNormEntity> saleGoodsNormEntities)
        {
            List<SaleGoodsNormEntity> result = new List<SaleGoodsNormEntity>();
            int i = 0;
            foreach (var entity in saleGoodsNormEntities)
            {
                entity.SaleGoodsCategoryId = goodsEntity.SaleGoodsCategoryId;
                entity.CategoryName = goodsEntity.CategoryName;
                entity.SaleGoodsId = goodsEntity.SaleGoodsId;
                entity.GoodsName = goodsEntity.GoodsName;
                entity.Sku = goodsEntity.Sku;
                entity.NormNamePinyin = Pinyin.GetCompactPinyin(entity.NormName);
                entity.NormNo = string.Format("{0}:{1}", entity.Sku, entity.NormNo);
                entity.NormIndex = i;
                entity.CreateAdminName = applicationContextService.Admin.FullName;
                entity.CreateAdminId = applicationContextService.Admin.AdminId;
                if (this.saleGoodsNormData.Exists(entity.NormNo).Result)
                {
                    throw new ArgumentException(string.Format("此销售商品规格编号已存在!规格编号：{0}", entity.NormNo));
                }
                this.CheckGoodsNormInfo(entity);
                result.Add(this.saleGoodsNormData.Add(entity).Result);
                i++;
            }
            return result;
        }
        #endregion

        #region 检查商品规格信息是否完整
        private void CheckGoodsNormInfo(SaleGoodsNormEntity entity)
        {
            if (entity.HasStepPrice)
            {
                if (!entity.StepOneStartNumber.HasValue || !entity.StepTwoStartNumber.HasValue || !entity.StepThreeStartNumber.HasValue)
                {
                    throw new ArgumentException(string.Format("商品规格 {0} 是阶梯价格，至少需填写一个阶梯开始数量!", entity.NormName));
                }
                if (!entity.StepOnePrice.HasValue || !entity.StepTwoPrice.HasValue || !entity.StepThreePrice.HasValue)
                {
                    throw new ArgumentException(string.Format("商品规格 {0} 是阶梯价格，至少需填写一个阶梯价格!", entity.NormName));
                }

                if (entity.StepOneStartNumber.HasValue&&entity.StepOneStartNumber.Value==0)
                {
                    throw new ArgumentException(string.Format("商品规格 {0} 是阶梯价格，但第一个阶梯开始数应大于0!", entity.NormName));
                }
                else if(entity.StepOneEndNumber.HasValue && entity.StepOneEndNumber.Value<= entity.StepOneStartNumber.Value)
                {
                    throw new ArgumentException(string.Format("商品规格 {0} 是阶梯价格，但第一个阶梯结束数应大于第一个阶梯开始数!", entity.NormName));
                }
                else if(entity.StepTwoStartNumber.HasValue&&entity.StepTwoStartNumber.Value<= entity.StepOneEndNumber.Value)
                {
                    throw new ArgumentException(string.Format("商品规格 {0} 是阶梯价格，但第二个阶梯开始数应大于第一个阶梯结束数!", entity.NormName));
                }
                else if(entity.StepTwoEndNumber.HasValue && entity.StepTwoEndNumber.Value <= entity.StepTwoStartNumber.Value)
                {
                    throw new ArgumentException(string.Format("商品规格 {0} 是阶梯价格，但第二个阶梯结束数应大于第二个阶梯开始数!", entity.NormName));
                }
                else if (entity.StepThreeStartNumber.HasValue && entity.StepThreeStartNumber.Value <= entity.StepTwoEndNumber.Value)
                {
                    throw new ArgumentException(string.Format("商品规格 {0} 是阶梯价格，但第三个阶梯开始数应大于第二个阶梯结束数!", entity.NormName));
                }
                else if (entity.StepThreeEndNumber.HasValue && entity.StepThreeEndNumber.Value <= entity.StepThreeStartNumber.Value)
                {
                    throw new ArgumentException(string.Format("商品规格 {0} 是阶梯价格，但第三个阶梯结束数应大于第三个阶梯开始数!", entity.NormName));
                }
            }
            if (string.IsNullOrWhiteSpace(entity.SaleUnit))
            {
                throw new ArgumentException(string.Format("商品规格 {0} 应填写销售单位!", entity.NormName));
            }
            if (entity.HasContentHeaderVideo&&(string.IsNullOrWhiteSpace(entity.ContentHeaderVideo)||entity.ContentHeaderVideo.Substring(entity.ContentHeaderVideo.LastIndexOf('.')+1)!="mp4"))
            {
                throw new ArgumentException(string.Format("商品规格 {0} 已启用内容顶部视频，却没有上传MP4格式视频文件!", entity.NormName));
            }
            if (entity.HasContentSummary && string.IsNullOrWhiteSpace(entity.ContentSummary))
            {
                throw new ArgumentException(string.Format("商品规格 {0} 已启用内容摘要，却没有填写任何摘要信息!", entity.NormName));
            }
            if (string.IsNullOrWhiteSpace(entity.Content))
            {
                throw new ArgumentException(string.Format("商品规格 {0} 内容信息不应为空!", entity.NormName));
            }
            if (entity.HasRelatedProducts&&string.IsNullOrWhiteSpace(entity.RelatedProductsIdPath))
            {
                throw new ArgumentException(string.Format("商品规格 {0} 已启用展示相关商品功能，却没有设置任何相关商品信息!", entity.NormName));
            }
        }
        #endregion

        #region 检查销售商品规格是否存在
        /// <summary>
        /// 是否存在此记录
        /// </summary>
        /// <param name="saleGoodsNormId">销售商品规格Id</param>
        public bool GoodsNormExists(long saleGoodsNormId)
        {
            return this.saleGoodsNormData.Exists(saleGoodsNormId).GetAwaiter().GetResult();
        }
        #endregion

        #region 添加销售商品规格
        public SaleGoodsNormDto AddGoodsNorm(SaleGoodsNormRequestDto requestDto)
        {
            if (!this.saleGoodsData.SKUExists(requestDto.Sku).Result)
            {
                throw new ArgumentException("此SKU商品不存在!");
            }

            var goodsEntity = this.saleGoodsData.GetEntity(requestDto.Sku).Result;

            var entity = requestDto.As<SaleGoodsNormEntity>();
            this.CheckGoodsNormInfo(entity);
            entity.SaleGoodsCategoryId = goodsEntity.SaleGoodsCategoryId;
            entity.CategoryName = goodsEntity.CategoryName;
            entity.SaleGoodsId = goodsEntity.SaleGoodsId;
            entity.GoodsName = goodsEntity.GoodsName;
            entity.Sku = goodsEntity.Sku;
            entity.NormNo = string.Format("{0}:{1}", goodsEntity.Sku, entity.NormNo);
            entity.NormNamePinyin = Pinyin.GetCompactPinyin(entity.NormName);

            if (this.saleGoodsNormData.Exists(entity.NormNo).Result)
            {
                throw new ArgumentException(string.Format("此销售商品规格编号已存在!规格编号：{0}", entity.NormNo));
            }
            var normEntities = this.saleGoodsNormData.GetList(entity.SaleGoodsId).Result;

            entity.NormIndex = normEntities.Max(p => p.NormIndex) + 1;
            entity.CreateAdminName = applicationContextService.Admin.FullName;
            entity.CreateAdminId = applicationContextService.Admin.AdminId;

            var result = this.saleGoodsNormData.Add(entity).GetAwaiter().GetResult();
            string cacheKey = this.redisService.GetSingleRootKey(normKey, "sku",entity.Sku);
            this.redisService.DeleteMultipleKey(cacheKey, false);
            cacheKey = this.redisService.GetSingleRootKey(normKey, "saleGoodsNormId", entity.SaleGoodsNormId);
            this.redisService.DeleteMultipleKey(cacheKey, false);
            return result.As<SaleGoodsNormDto>();
        }
        #endregion

        #region 修改销售商品规格
        public SaleGoodsNormDto UpdateGoodsNorm(SaleGoodsNormPutDto putDto)
        {
            if (!this.GoodsNormExists(putDto.SaleGoodsNormId))
            {
                throw new ArgumentException("此记录不存在!");
            }

            if (!this.saleGoodsData.SKUExists(putDto.Sku).Result)
            {
                throw new ArgumentException("此SKU商品不存在!");
            }

            var goodsEntity = this.saleGoodsData.GetEntity(putDto.Sku).Result;

            var oldGoodsNormEntity = this.saleGoodsNormData.GetEntity(putDto.SaleGoodsNormId).Result;

            var entity = putDto.As<SaleGoodsNormEntity>();
            this.CheckGoodsNormInfo(entity);
            if (putDto.NormNo.IndexOf(":") > -1)
            {
                putDto.NormNo = putDto.NormNo.Split(':')[1];
            }
            entity.NormNo = string.Format("{0}:{1}", goodsEntity.Sku, entity.NormNo);

            if (goodsEntity.Sku!=oldGoodsNormEntity.Sku)
            {
                if (this.saleShoppingCartData.GoodsNormExists(putDto.SaleGoodsNormId).Result)
                {
                    throw new ArgumentException("此商品已存在销售记录，不允许更改所属商品!");
                }
                var normEntities = this.saleGoodsNormData.GetList(oldGoodsNormEntity.SaleGoodsId).Result;
                var enabledEntities = normEntities.Where(p => p.Enabled);
                if (enabledEntities != null && enabledEntities.Any())
                {
                    var mainNormEntity = enabledEntities.OrderBy(p => p.NormIndex).First();
                    if (mainNormEntity.NormIndex == oldGoodsNormEntity.NormIndex)
                    {
                        throw new ArgumentException("此商品规格已启用，请先禁用后再进行修改!");
                    }
                }

                var goodsInCartExists = false;
                if (goodsInCartExists)
                {
                    throw new ArgumentException("此商品已存在销售记录，不允许更改商品SKU!");
                }
                entity.SaleGoodsCategoryId = oldGoodsNormEntity.SaleGoodsCategoryId;
                entity.CategoryName = oldGoodsNormEntity.CategoryName;
                entity.SaleGoodsId = oldGoodsNormEntity.SaleGoodsId;
                entity.GoodsName = oldGoodsNormEntity.GoodsName;
                entity.NormNamePinyin = Pinyin.GetCompactPinyin(entity.NormName);
                if (this.saleGoodsNormData.Exists(entity.NormNo).Result)
                {
                    throw new ArgumentException(string.Format("此销售商品规格编号已存在!规格编号：{0}", entity.NormNo));
                }

                entity.NormIndex = normEntities.Max(p => p.NormIndex) + 1;
            }
            else
            {
                entity.SaleGoodsCategoryId = goodsEntity.SaleGoodsCategoryId;
                entity.CategoryName = goodsEntity.CategoryName;
                entity.SaleGoodsId = goodsEntity.SaleGoodsId;
                entity.GoodsName = goodsEntity.GoodsName;
                entity.Sku = goodsEntity.Sku;
                entity.NormNamePinyin = Pinyin.GetCompactPinyin(entity.NormName);
                if (this.saleGoodsNormData.Exists(entity.NormNo).Result)
                {
                    throw new ArgumentException(string.Format("此销售商品规格编号已存在!规格编号：{0}", entity.NormNo));
                }
            }
            entity.EditAdminName = applicationContextService.Admin.FullName;
            entity.EditAdminId = applicationContextService.Admin.AdminId;

            var result = this.saleGoodsNormData.Update(entity).GetAwaiter().GetResult().As<SaleGoodsNormDto>();
            string cacheKey = this.redisService.GetSingleRootKey(normKey, "sku", entity.Sku);
            this.redisService.DeleteMultipleKey(cacheKey, false);
            cacheKey = this.redisService.GetSingleRootKey(normKey, "saleGoodsNormId", entity.SaleGoodsNormId);
            this.redisService.DeleteMultipleKey(cacheKey, false);
            return result;
        }
        #endregion
        #region 删除销售商品规格
        public bool DeleteGoodsNorm(long saleGoodsNormId)
        {
            if (!this.GoodsNormExists(saleGoodsNormId))
            {
                throw new ArgumentException("此记录不存在!");
            }
            if (this.saleShoppingCartData.GoodsNormExists(saleGoodsNormId).Result)
            {
                throw new ArgumentException("此商品已存在销售记录，不允许删除商品规格，仅支持禁用!");
            }
            var dto = this.GetGoodsNorm(saleGoodsNormId);
            var result = this.saleGoodsNormData.Delete(saleGoodsNormId).GetAwaiter().GetResult();
            string cacheKey = this.redisService.GetSingleRootKey(normKey, "sku", dto.Sku);
            this.redisService.DeleteMultipleKey(cacheKey, false);
            cacheKey = this.redisService.GetSingleRootKey(normKey, "saleGoodsNormId", dto.SaleGoodsNormId);
            this.redisService.DeleteMultipleKey(cacheKey, false);
            return result;
        }
        #endregion

        #region 获取销售商品规格
        public SaleGoodsNormDto GetGoodsNorm(long saleGoodsNormId)
        {
            string cacheKey = this.redisService.GetKey(normKey, saleGoodsNormId);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var data = this.saleGoodsNormData.GetEntity(saleGoodsNormId).GetAwaiter().GetResult();
                return data;
            }, TimeSpan.FromMinutes(30));
            return result.As<SaleGoodsNormDto>();
        }
        #endregion

        #region 获取销售商品规格列表
        public IEnumerable<SaleGoodsNormDto> GetGoodsNormList(long saleGoodsId)
        {
            string cacheKey = this.redisService.GetKey(normKey, saleGoodsId);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                return this.saleGoodsNormData.GetList(saleGoodsId).GetAwaiter().GetResult();
            }, TimeSpan.FromMinutes(30));
            return result.As<IEnumerable<SaleGoodsNormDto>>();
        }
        #endregion

        #region 获取销售商品规格分页
        public PageableList<SaleGoodsNormDto> QueryGoodsNorm(string sku, string categoryName,string goodsName, bool? enabled, DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
        {
            string cacheKey = this.redisService.GetKey(normKey, sku, categoryName, goodsName, enabled, start, end, sortName, ascending, pageIndex, pageSize);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var data = this.saleGoodsNormData.Query(categoryName, goodsName, sku, enabled, start, end, sortName, ascending, pageIndex, pageSize).GetAwaiter().GetResult();
                return new PageableList<SaleGoodsNormDto>
                {
                    Count = data.Item2,
                    Items = data.Item1.As<IEnumerable<SaleGoodsNormDto>>(),
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    ServerTime = DateTime.Now
                };
            }, TimeSpan.FromMinutes(30));

            return result;
        }
        #endregion

        #region 启用销售商品规格
        public bool EnabledGoodsNorm(long saleGoodsNormId)
        {
            if (!this.GoodsNormExists(saleGoodsNormId))
            {
                throw new ArgumentException("此记录不存在!");
            }
            var oldGoodsNormDto = this.GetGoodsNorm(saleGoodsNormId);

            var goodsDto = this.Get(oldGoodsNormDto.SaleGoodsId);

            databaseContext.BeginTransaction();

            var result = this.saleGoodsNormData.Enabled(saleGoodsNormId).GetAwaiter().GetResult();

            var oldGoodsNormEntities = this.saleGoodsNormData.GetList(oldGoodsNormDto.SaleGoodsId).Result;
            if (oldGoodsNormEntities.Any())
            {
                var enabledGoodsNormEntities = oldGoodsNormEntities.Where(p => p.Enabled).ToList();
                var firstNormEntity = enabledGoodsNormEntities.First();
                var goodsEntity = goodsDto.As<SaleGoodsEntity>();
                this.ResetGoodsDisplayInfo(goodsEntity, firstNormEntity, enabledGoodsNormEntities);
                this.saleGoodsData.Update(goodsEntity).GetAwaiter().GetResult();
            }
            this.saleShoppingCartData.UpdateSaleGoodsDisabled(goodsDto.SaleGoodsId,saleGoodsNormId, false).GetAwaiter().GetResult();
            databaseContext.Commit();

            string cacheKey = this.redisService.GetSingleRootKey(normKey, "sku", goodsDto.Sku);
            this.redisService.DeleteMultipleKey(cacheKey, false);
            cacheKey = this.redisService.GetSingleRootKey(normKey, "saleGoodsNormId", saleGoodsNormId);
            this.redisService.DeleteMultipleKey(cacheKey, false);
            return result;
        }
        #endregion

        #region 禁用销售商品规格
        public bool DisabledGoodsNorm(long saleGoodsNormId)
        {
            if (!this.GoodsNormExists(saleGoodsNormId))
            {
                throw new ArgumentException("此记录不存在!");
            }

            var oldGoodsNormDto = this.GetGoodsNorm(saleGoodsNormId);
            var goodsDto = this.Get(oldGoodsNormDto.SaleGoodsId);

            databaseContext.BeginTransaction();

            var result = this.saleGoodsNormData.Disabled(saleGoodsNormId).GetAwaiter().GetResult();

            var oldGoodsNormEntities = this.saleGoodsNormData.GetList(oldGoodsNormDto.SaleGoodsId).Result;
            if (oldGoodsNormEntities.Any())
            {
                var enabledGoodsNormEntities = oldGoodsNormEntities.Where(p => p.Enabled).ToList();
                var firstNormEntity = enabledGoodsNormEntities.First();
                var goodsEntity = goodsDto.As<SaleGoodsEntity>();
                this.ResetGoodsDisplayInfo(goodsEntity, firstNormEntity, enabledGoodsNormEntities);
                this.saleGoodsData.Update(goodsEntity).GetAwaiter().GetResult();
            }
            this.saleShoppingCartData.UpdateSaleGoodsDisabled(goodsDto.SaleGoodsId, saleGoodsNormId, true).GetAwaiter().GetResult();
            databaseContext.Commit();

            string cacheKey = this.redisService.GetSingleRootKey(normKey, "sku", goodsDto.Sku);
            this.redisService.DeleteMultipleKey(cacheKey, false);
            cacheKey = this.redisService.GetSingleRootKey(normKey, "saleGoodsNormId", saleGoodsNormId);
            this.redisService.DeleteMultipleKey(cacheKey, false);
            return result;
        }
        #endregion

        #region 重新赋值商品展示信息
        private void ResetGoodsDisplayInfo(SaleGoodsEntity entity,SaleGoodsNormEntity mainGoodsNormEntity,List<SaleGoodsNormEntity> saleGoodsNormEntities)
        {
            entity.HasBargain = mainGoodsNormEntity.HasBargain;
            if (!entity.HasBargain)
            {
                entity.HasStepPrice = mainGoodsNormEntity.HasStepPrice;
                if (entity.HasStepPrice)
                {
                    if (!mainGoodsNormEntity.StepOneEndNumber.HasValue || !mainGoodsNormEntity.StepTwoStartNumber.HasValue || !mainGoodsNormEntity.StepThreeStartNumber.HasValue)
                    {
                        throw new ArgumentException(string.Format("商品规格 {0} 是阶梯价格，至少需填写一个阶梯开始数量", mainGoodsNormEntity.NormName));
                    }
                    if (!mainGoodsNormEntity.StepOnePrice.HasValue || !mainGoodsNormEntity.StepTwoPrice.HasValue || !mainGoodsNormEntity.StepThreePrice.HasValue)
                    {
                        throw new ArgumentException(string.Format("商品规格 {0} 是阶梯价格，至少需填写一个阶梯价格", mainGoodsNormEntity.NormName));
                    }
                    if (!mainGoodsNormEntity.StepOneStartNumber.HasValue && !mainGoodsNormEntity.StepOneEndNumber.HasValue &&
                        (mainGoodsNormEntity.StepTwoStartNumber.HasValue || mainGoodsNormEntity.StepTwoEndNumber.HasValue
                        || mainGoodsNormEntity.StepThreeStartNumber.HasValue || mainGoodsNormEntity.StepThreeEndNumber.HasValue))
                    {
                        throw new ArgumentException(string.Format("商品规格 {0} 是阶梯价格，请从第一阶梯开始填写数量", mainGoodsNormEntity.NormName));
                    }
                    if (mainGoodsNormEntity.StepOneStartNumber.HasValue && mainGoodsNormEntity.StepOneEndNumber.HasValue &&
                        !mainGoodsNormEntity.StepTwoStartNumber.HasValue && !mainGoodsNormEntity.StepTwoEndNumber.HasValue
                        &&(mainGoodsNormEntity.StepThreeStartNumber.HasValue || mainGoodsNormEntity.StepThreeEndNumber.HasValue))
                    {
                        throw new ArgumentException(string.Format("商品规格 {0} 是阶梯价格，请补齐第二阶梯填写数量", mainGoodsNormEntity.NormName));
                    }
                    if (mainGoodsNormEntity.StepOneEndNumber.HasValue&& !mainGoodsNormEntity.StepOnePrice.HasValue)
                    {
                        throw new ArgumentException(string.Format("商品规格 {0} 是阶梯价格，且第一组阶梯数量已填写，但并未填写第一组价格", mainGoodsNormEntity.NormName));
                    }
                    if ((mainGoodsNormEntity.StepTwoStartNumber.HasValue|| mainGoodsNormEntity.StepTwoEndNumber.HasValue) && !mainGoodsNormEntity.StepTwoPrice.HasValue)
                    {
                        throw new ArgumentException(string.Format("商品规格 {0} 是阶梯价格，且第二组阶梯数量已填写，但并未填写第二组价格", mainGoodsNormEntity.NormName));
                    }
                    if ((mainGoodsNormEntity.StepThreeStartNumber.HasValue || mainGoodsNormEntity.StepThreeEndNumber.HasValue) && !mainGoodsNormEntity.StepThreePrice.HasValue)
                    {
                        throw new ArgumentException(string.Format("商品规格 {0} 是阶梯价格，且第三组阶梯数量已填写，但并未填写第三组价格", mainGoodsNormEntity.NormName));
                    }
                    entity.StepOneStartNumber = mainGoodsNormEntity.StepOneStartNumber;
                    entity.StepOneEndNumber = mainGoodsNormEntity.StepOneEndNumber;
                    entity.StepTwoStartNumber = mainGoodsNormEntity.StepTwoStartNumber;
                    entity.StepTwoEndNumber = mainGoodsNormEntity.StepTwoEndNumber;
                    entity.StepThreeStartNumber = mainGoodsNormEntity.StepThreeStartNumber;
                    entity.StepThreeEndNumber = mainGoodsNormEntity.StepThreeEndNumber;
                    entity.StepOnePrice = mainGoodsNormEntity.StepOnePrice;
                    entity.StepTwoPrice = mainGoodsNormEntity.StepTwoPrice;
                    entity.StepThreePrice = mainGoodsNormEntity.StepThreePrice;
                }
                else
                {
                    entity.SaleAmount = mainGoodsNormEntity.SaleAmount;
                }
            }
            entity.SaleUnit = mainGoodsNormEntity.SaleUnit;
            entity.HasContentHeaderVideo = mainGoodsNormEntity.HasContentHeaderVideo;
            entity.ContentHeaderVideo = mainGoodsNormEntity.ContentHeaderVideo;
            entity.HasContentSummary = mainGoodsNormEntity.HasContentSummary;
            entity.ContentSummary = mainGoodsNormEntity.ContentSummary.Trim().TrimEnd(',');
            entity.Content = mainGoodsNormEntity.Content;
            entity.HasRelatedProducts = mainGoodsNormEntity.HasRelatedProducts;
            entity.RelatedProductsIdPath = mainGoodsNormEntity.RelatedProductsIdPath.Trim().TrimEnd(',');
            entity.InventoryCount = mainGoodsNormEntity.InventoryCount;
            entity.SaleCount = mainGoodsNormEntity.SaleCount;

            #region 循环赋值首图
            for (int i = 0; i < saleGoodsNormEntities.Count; i++)
            {
                if (i == 0)
                {
                    entity.OneImage = saleGoodsNormEntities[i].MainImage;
                }
                if (i == 1)
                {
                    entity.TwoImage = saleGoodsNormEntities[i].MainImage;
                }
                if (i == 2)
                {
                    entity.ThreeImage = saleGoodsNormEntities[i].MainImage;
                }
                if (i == 3)
                {
                    entity.FourImage = saleGoodsNormEntities[i].MainImage;
                }
                if (i == 4)
                {
                    entity.FiveImage = saleGoodsNormEntities[i].MainImage;
                }
            }
            #endregion
        }
        #endregion
        #endregion
    }
}